import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { BladeData } from "../../../../shared/blade/blade-data";
import { Blade } from "../../../../shared/blade/blade.model";
import { Command } from "../../../../shared/toolbar.service";
import { ModelService } from "../../../../service/model.service";
import { Model } from "../../../../entity/model.model";
import { DialogResult } from "../../../../shared/dialog.service";
import { SchemeService } from "../../../../service/scheme.service";
import { Scheme } from "../../../../entity/scheme.model";
import { StateInfoGroupEditComponent } from "./state-info-group-edit/state-info-group-edit.component";
import { StateInfoListComponent } from "./state-info-list/state-info-list.component";
@Component({
  selector: 'app-state-info',
  templateUrl: './state-info.component.html',
  styleUrls: ['./state-info.component.css']
})
export class StateInfoComponent extends BladeContainerBase<Model>  {
  schemes: Scheme[] = [];
  currentScheme: Scheme;
  defaultChecked: Scheme;
  constructor(
    private modelService: ModelService,
    private schemeService: SchemeService,
  ) {
    super()
  }

  ngOnInit() {
    this.commands = [
      new Command("add", "添加", "fa fa-plus", "setofkey:insert", blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
      new Command("edit", "编辑", "fa fa-edit", "setofkey:update", blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
      new Command("delete", "删除", "fa fa-trash-o", "setofkey:delete", blade => this.exeDelete(blade), blade => this.canDelete(blade)),
    ];
    super.ngOnInit();
  }
  initData(): any {
    this.schemes=[]
    this.defaultChecked=null;
    let getSchemes = this.schemeService.getSchemesByCategoryId(2)
    let getDefault = this.schemeService.getSchemesBymModelIdCategoryId(this.currentEntity.modelId, 2);
   Promise.all([getSchemes, getDefault])
      .then(res => {
        this.bladeData.isLoading = false;
        this.schemes = [...res[0]];
        this.schemes.forEach(scheme=>{
          scheme.defaultValue=false;
        })
        
        if (res[1]) {
          this.defaultChecked = res[1];
          let i = this.schemes.findIndex(o => o.schemeId == this.defaultChecked.schemeId);
          if (i > -1) {
            this.currentScheme = this.schemes[i];
            this.schemes[i].defaultValue = true;
            this.currentEntity.hasDefault = true;
          } else {
            
            this.currentScheme = this.schemes[0];

          }
        } else {
          this.currentScheme = this.schemes[0];
          this.currentEntity.hasDefault=false;
        }
        this.exeStandardCurveList(this.currentScheme)
      })
      .catch(err => {
        console.log("app-standard-curve" + err)
      })
  }
  exeAdd(blend: Blade): void {
    let data: BladeData = new BladeData();
    data.id = "scGroupEdit";
    data.title = "创建状态信息分组";
    data.isClosingDisabled = false;
     let parentData: ParentData = {
      current: this.currentEntity,
      defaultChecked: this.defaultChecked,
    }
    let createKeyBlade = this.bladeService.createBlade(StateInfoGroupEditComponent, data, true, this.currentScheme, parentData);
    this.bladeService.showBlade(createKeyBlade, this.currentBlade);
  }
  canExeAdd(blend: Blade): boolean {
    return true;
  }
  exeEdit(blend: Blade): void {
    if (this.currentEntity != undefined) {
      let data: BladeData = new BladeData();
      data.id = "sIGroupEdit";
      data.title = this.currentEntity.modelName;//当前分组名称
      let parentData: ParentData = {
      current: this.currentEntity,
      defaultChecked: this.defaultChecked,
    }
      let editKeyBlade = this.bladeService.createBlade(StateInfoGroupEditComponent, data, false, this.currentScheme, parentData);
      this.currentBlade.bladeService.showBlade(editKeyBlade, this.currentBlade);

    }
  }
  canExeEdit(blend?: Blade): boolean {
    return this.currentEntity != null;
  }
  exeDelete(blend: Blade): void {
    let selectedKeys = this.getSelected();
    if (selectedKeys.length > 0) {
      this.dialogService
        .showConfirmationDialog("确认删除", "是否要删除选中项？")
        .subscribe(dialogResult => {
          if (dialogResult == DialogResult.Ok) {
            this.currentBlade.bladeData.isLoading = true;
            this.schemeService.batchDelete(selectedKeys.map(o => o.schemeId))
              .then(res => {
                if (res.code == '200') {
                  super.refresh(this.currentEntity);
                }
                if(res.code=='8001'){
                  this.dialogService
                  .showConfirmationDialog("删除失败", res.message);
                }
               
              })
              .catch(error => this.bladeData.error = error)
              .then(res => this.bladeData.isLoading = false);
          }
        })
    }
  }
  canDelete(blend?: Blade): boolean {
    return this.getSelected().length > 0;

  }

  onSeletedChange(selectedKey?: Scheme) {
    if (this.currentBlade.childrenCanDeactivate()) {
      this.exeStandardCurveList(selectedKey);
    }
  }
  exeStandardCurveList(selectedKey: Scheme) {
    if (this.currentScheme != selectedKey
      || this.bladeService.findBlade("stateInfoList") == undefined) {
      let data: BladeData = new BladeData();
      data.id = "stateInfoList";
      data.title = selectedKey.schemeName;
      data.isClosingDisabled = false;
      let turbstatusCheckBlade = this.bladeService.createBlade(StateInfoListComponent, data, false, selectedKey, this.currentEntity);
      this.bladeService.showBlade(turbstatusCheckBlade, this.currentBlade).then(res => {
        if (res) {
          this.currentScheme = selectedKey;
        }
      });

    }
  }
  onItemCheack(event: HTMLInputElement, key: Scheme) {
    key.isChecked = event.checked;
  }
  /**
   * 
   *获得选中项 
   * @returns {Scheme[]} 
   * @memberof StateInfoComponent
   */
  getSelected(): Scheme[] {
    if (this.schemes.length > 0) {
      let filter = this.schemes.filter(ref => ref.isChecked)
      return filter == null ? [] : filter;
    }
    return [];
  }
  onAllCheack(event: HTMLInputElement) {
    if (this.schemes.length > 0) {
      for (let i = 0; i < this.schemes.length; i++) {
        this.schemes[i].isChecked = event.checked;
      }
    }
  }
}
interface ParentData {
  current: Model,
  defaultChecked: Scheme,
}



// WEBPACK FOOTER //
// ./src/app/module/basic/model/state-info/state-info.component.ts